<?php

namespace Repository;

use Doctrine\ORM\Tools\Pagination\Paginator;

use Doctrine\Common\Cache\ArrayCache,
	Doctrine\ORM\EntityRepository,
	DoctrineExtensions\Paginate\Paginate as Paginate,
	ST;

class CommonRepository extends EntityRepository
{   
	public function getPaginator($entity, $offset = 0, $limit = 20, $order = false)
	{
		if($offset == 1){
			$offset = 0;
		}
		if($order){
			$sql = 'SELECT e FROM ' . $entity . ' e ' .
					'ORDER BY e.numorder ASC';
		}else{
			$sql = 'SELECT e FROM ' . $entity . ' e ' .
					'ORDER BY e.id ASC';
		}
			
		//$queryBuilder = $this->_em->createQueryBuilder();
	
		$query = $this->_em->createQuery($sql)
		->setMaxResults($limit)
		->setFirstResult($offset);
	
		$paginator = new Paginator($query);
	
		return $paginator;
	}

	public function getBy($params, $join_tables = null){
        $filters = $params['filter'];
        $paging = $params['paging'];
        $order = $params['order'];
        $default_conditions = @$params['default_conditions'];

        $entity_name = $this->getEntityName();

        $qb = $this->_em->createQueryBuilder();
        $qb->from($entity_name, 'o');
        $select = array('o');
        /* join tables like
            $join_tables = array(
                array(
                    'entity' => entity,
                    'primary_column' => primary table column,
                    'join_column' => join table column,
                    'title' => title (as alias)
                ),
                ...
            );
        */
// print_r($join_tables);die;
        if($join_tables != null){
            foreach($join_tables as $key => $table){
                $table_alias = strtolower(str_replace('\Entity\St', '', $table['entity'])) . '_' . str_replace(array(' ', ','), '', $table['title']);
                // $table_alias = 'j' . $key;
                $qb->leftJoin($table['entity'], $table_alias, 'with', $qb->expr()->eq('o.' . $table['primary_column'], $table_alias . '.' . $table['join_column']));
                // echo 'o.' . $table['primary_column'] . ' = ' . $table_alias . '.' . $table['join_column'] . PHP_EOL;
                // echo $table['entity'] . ' ' . $table_alias . PHP_EOL;
                if(isset($table['join_column']) && $table['join_column'] != ''){
                    // $qb->andWhere($qb->expr()->eq('o.' . $table['primary_column'], $table_alias . '.' . $table['join_column']));
                    if(isset($filters['lang']) && $filters['lang'] != ''){
                        $qb->andWhere($qb->expr()->eq($table_alias . '.lang', $filters['lang']));
                    }
                }
                $table['title'] = explode(',', $table['title']);
                foreach($table['title'] as $title){
                    $select[] = $table_alias . '.' . trim($title);
                }
            }
        }
        // print_r($select);
        $qb ->select(implode(',', $select));
        // print_r($select);die;
        if(!empty($filters)){
            foreach($filters as $index => $filter){
                if($filter['entity'] == ''){
                    $filter['entity'] = 'o';
                }else{
                    $filter['entity'] = strtolower(str_replace('\Entity\St', '', $filter['entity']));
                    $filter['entity'] .= '_' . str_replace(array(' ', ','), '', $filter['title']);
                }
                switch($index){
                    case 'ids':
                        $qb->andWhere($qb->expr()->in($filter['entity'] . '.' . $filter['name'], $filter['value']));
                        break;
                    default:
                        if(!isset($filter['value']['lt']) && !isset($filter['value']['gt']) && !isset($filter['value']['eq']) && !isset($filter['value']['in'])){
                            if(isset($filter['value']) && $filter['value'] != ''){
                                $filter['value'] = ST\Utilities::strToTimeIfIsDate($filter['value'], 'd-m-Y');
                                if(is_numeric($filter['value'])){
                                    $qb->andWhere($qb->expr()->between($filter['entity'] . '.' . $filter['name'], $filter['value'], $filter['value'] + (24 * 3600)));
                                }else{
                                    $qb->andWhere($qb->expr()->like($filter['entity'] . '.' . $filter['name'], $qb->expr()->literal('%' . $filter['value'] . '%')));
                                }
                            }
                        }else{
                            if(is_array($filter['value'])){
                                if (@$filter['value']['lt'] != '' && @$filter['value']['gt'] != ''){
                                    $qb->andWhere($qb->expr()->between($filter['entity'] . '.' . $filter['name'], $filter['value']['gt'], $filter['value']['lt']));
                                 }
                                 elseif(@$filter['value']['lt'] != ''){
                                    $qb->andWhere($qb->expr()->lte($filter['entity'] . '.' . $filter['name'], $filter['value']['lt']));
                                 }
                                 elseif(@$filter['value']['gt'] != ''){
                                     $qb->andWhere($qb->expr()->gte($filter['entity'] . '.' . $filter['name'], $filter['value']['gt']));
                                 }
                                 elseif (@$filter['value']['eq'] != '')
                                 {
                                     $qb->andWhere($qb->expr()->eq($filter['entity'] . '.' . $filter['name'], $filter['value']['eq']));
                                 }
                                 elseif(!empty($filter['value']['in'])){
                                    $qb->andWhere($qb->expr()->in($filter['entity'] . '.' . $filter['name'], $filter['value']['in']));
                                 }
                            }
                         }
                        break;
                }
            }
            if(!empty($default_conditions)){
                foreach($default_conditions as $condition){
                    $qb->andWhere($qb->expr()->{$condition['op']}('o.' . $condition['name'], $condition['value']));
                }
            }

            $qb->orderBy($order['orderby'], $order['orderdir']);
        
        }
        if($paging['length'] > 0)
        {
            $qb ->setFirstResult($paging['start'])
                ->setMaxResults($paging['length']);
        }
        // echo $qb->getQuery()->getSQL();die;
        $paginator = new Paginator($qb->getQuery(),false);
        // echo count($paginator);die;
        return $paginator;
    }

    public function count(){
        $entity_name = $this->getEntityName();
        $query = $this->_em->createQuery('SELECT COUNT(o.id) FROM ' . $entity_name . ' o');
        return $query->getSingleScalarResult();
    }
	
}